package day04;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Serverall {
	ServerSocket ss;

	Map<String, Socket> map = new HashMap<String, Socket>();

	public Serverall(int port) throws IOException {
		ss=new ServerSocket(port);

	}
	
	public void sta() {
		System.out.println("聊天室已开放");
		while(true) {
			try {
				Socket s=ss.accept();
				BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
				String name=br.readLine();
				map.put(name, s);
				System.out.println(name + "上线了，聊天室当前有" + map.size() + "个人");
				new SThread(s, name).start();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
	}
	private class SThread extends Thread {
		private Socket s;
		private String name ;
		private BufferedReader br;
		
		public SThread(Socket s,String name) {
			this.s=s;
			this.name=name;
			try {
				init();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	    public void init() throws IOException {	    	
	    	br =new BufferedReader(new InputStreamReader(s.getInputStream()));
	    }	    
	    public void run() {
	    	while(true) {
	    		String message= getmessage();
	    		Set<String> names=map.keySet();
	    		for(String name :names) {
	    			Socket s=map.get(name);
	    			sendmessage(s,this.name+"说："+message);
	    		}	    			    		
	    	}
	    }
	    public void sendmessage(Socket s,String message) {
			 PrintWriter pw = null;
	    	try {
				pw=new PrintWriter(s.getOutputStream(),true);
			} catch (IOException e) {
				e.printStackTrace();
			}
	    	pw.println(message);
	    }
	    public String getmessage() {
			try {
				return br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
	    	
	    }

    }

	public static void main(String[] args) throws IOException {	
		System.out.println("----这里是服务器----");
		new Serverall(9800).sta();
		
	}

}
